package cn.zlh.export;

import cn.zlh.ht.service.TemplateService;
import io.swagger.annotations.Api;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHighlightColor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

/**
 * @author 张乐焕

 */
@Slf4j
@RestController
@Api(tags = "合同word导出接口")
@RequestMapping("/zlh/word")
public class WordExportController {

    @Autowired
    TemplateService templateService;

    @PostMapping("/export")
    public void exportWord(@RequestBody Map<String, Object> param, HttpServletResponse response) throws IOException {
        // 获取字段值
        String title = (String) param.get("title");
        String createBy = (String) param.get("createBy");
        String createTime = String.valueOf(param.get("createTime"));
        String firstParty = (String) param.get("firstParty");
        String secondParty = (String) param.get("secondParty");
        String date = String.valueOf(param.get("date"));
        String auditStatus = (String) param.get("auditStatus");
        String auditUser = (String) param.get("auditUser");
        String auditTime = String.valueOf(param.get("auditTime"));
        String signStatus = (String) param.get("signStatus");
        String signTime = String.valueOf(param.get("signTime"));
        String signUser = (String) param.get("signUser");
        Integer dateTemp = null;
        try {
            dateTemp = Integer.parseInt(String.valueOf(param.get("dateTemp")));
        } catch (NumberFormatException e) {
            dateTemp = null; // 如果解析失败，设置为 null 或根据需求处理
        }

        XWPFDocument document = new XWPFDocument();

        // 标题
        XWPFParagraph titlePara = document.createParagraph();
        titlePara.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titlePara.createRun();
        titleRun.setBold(true);
        titleRun.setFontSize(20);
        titleRun.setText(title != null ? title : "合同文档");
        titleRun.addBreak();

        // 写字段（非空才写入）
        addField(document, "合同创建人", createBy);
        addField(document, "合同创建时间", createTime);
        addField(document, "甲方", firstParty);
        addField(document, "乙方", secondParty);
        addField(document, "合同截止日期", date);
        addField(document, "审批状态", auditStatus);
        addField(document, "审批人", auditUser);
        addField(document, "审批时间", auditTime);
        addField(document, "签订状态", signStatus);
        addField(document, "签订时间", signTime);
        addField(document, "合同发起人", signUser);
        if (dateTemp != null && dateTemp >= 0) {
            addField(document, "合同剩余时间", String.valueOf(dateTemp));
        }

        String tableName = (String) param.get("tableName");
        if (tableName != null) {
            String id = (String) param.get("id");
            Object templateDataByAgreemetnId = templateService.getTemplateDataByAgreemetnId(tableName, id);
            if (templateDataByAgreemetnId instanceof Map) {
                Map<String, Object> templateData = (Map<String, Object>) templateDataByAgreemetnId;
                // 假设你想将 templateData 中的每个键值对作为字段添加到文档中
                for (Map.Entry<String, Object> entry : templateData.entrySet()) {
                    // 跳过键名为 'tableCN' 的键值对
                    if (!"tableCN".equals(entry.getKey())) {
                        addField(document, entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : "N/A");
                    }
                }
            }
        }

        // 十个条款
        addParagraph(document, "一、合同双方");
        addContent(document, "甲方为项目发包单位，乙方为提供劳务服务的承包单位。双方在平等自愿的基础上签订本合同，并共同遵守。");

        addParagraph(document, "二、工程内容及要求");
        addContent(document, "乙方应根据甲方提供的工程任务和技术要求，按时、保质完成相应劳务工作，确保施工过程规范、安全。");

        addParagraph(document, "三、工期");
        addContent(document, "具体施工工期以甲乙双方约定为准。乙方需严格按照进度计划执行，如有延误需提前告知并取得甲方同意。");

        addParagraph(document, "四、履约义务与配合");
        addContent(document, "乙方应严格履行本合同项下的义务，合理安排资源，确保按时完成各项工作任务。施工过程中，应配合甲方的现场管理、进度控制和质量监督，保持良好的协作关系。乙方应主动解决履约中出现的问题，确保合同顺利履行。");

        addParagraph(document, "五、质量标准与验收");
        addContent(document, "工程质量应符合国家现行规范和甲方要求。项目完成后，甲方将组织验收，验收合格视为工程完成。");

        addParagraph(document, "六、违约责任");
        addContent(document, "任何一方违反合同约定，应承担违约责任。给对方造成经济损失的，还应承担相应赔偿责任。");

        addParagraph(document, "七、安全生产与管理");
        addContent(document, "乙方应建立健全安全生产责任制，严格遵守国家有关法律法规，避免各类安全事故发生。因管理不善造成的后果由乙方自行承担。");

        addParagraph(document, "八、保密条款");
        addContent(document, "乙方在履约过程中知悉的甲方商业信息、技术资料等，应予以保密，未经甲方书面许可不得向任何第三方披露。");

        addParagraph(document, "九、争议解决方式");
        addContent(document, "合同履行过程中如有争议，双方应协商解决；协商不成时，可提交甲方所在地人民法院处理。");

        addParagraph(document, "十、其他条款");
        addContent(document, "本合同自双方签字盖章之日起生效，合同一式两份，甲乙双方各执一份，具有同等法律效力。");

        // 响应导出
        response.setHeader("Content-Disposition", "attachment; filename=contract.docx");
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");

        document.write(response.getOutputStream());
        document.close();
    }

    private void addField(XWPFDocument document, String label, String value) {
        if (value != null && !value.trim().isEmpty() && !"null".equalsIgnoreCase(value)) {
            XWPFParagraph para = document.createParagraph();
            para.setSpacingAfter(100); // 增加段落间距
            XWPFRun run = para.createRun();

            run.setBold(true);
            run.setFontSize(13);
            run.setText(label + "：");

            XWPFRun valueRun = para.createRun();
            valueRun.setFontSize(13);

            // 状态字段：红/绿标色
            if ("审批状态".equals(label) || "签订状态".equals(label)) {
                valueRun.setText(value);
                if (value.contains("已")) {
                    valueRun.setColor("00B050"); // 绿色
                } else if (value.contains("未")) {
                    valueRun.setColor("FF0000"); // 红色
                } else {
                    valueRun.setColor("000000"); // 黑色默认
                }
                return;
            }

            // 用黄色背景框强调的人名类字段
            if ("审批人".equals(label) || "合同发起人".equals(label) || "合同创建人".equals(label)) {
                valueRun.setText(value);
                valueRun.setColor("000000");
                valueRun.getCTR().addNewRPr().addNewHighlight().setVal(STHighlightColor.Enum.forString("yellow"));
                return;
            }

            // 默认展示
            valueRun.setText(value);
        }
    }



    /**
     * @author: 张乐焕
     * @Description: 添加基础文本内容
     * @Date: 2023/8/19 12:12
     * @Param:
     * @return:
     */
    private void addContent(XWPFDocument doc, String text) {
        XWPFParagraph para = doc.createParagraph();
        para.setFirstLineIndent(400); // 首行缩进
        XWPFRun run = para.createRun();
        run.setFontSize(12);
        run.setText(text);
    }

    /**
     * @author: 张乐焕
     * @Description: 添加段落
     * @Date: 2023/8/19 12:11
     * @Param:
     * @return:
     */
    private void addParagraph(XWPFDocument doc, String text) {
        XWPFParagraph para = doc.createParagraph();
        para.setSpacingBefore(200);
        XWPFRun run = para.createRun();
        run.setBold(true);
        run.setFontSize(14);
        run.setText(text);
    }

    /**
     * @author: 张乐焕
     * @Description: 添加动态表格
     * @Date: 2023/8/19 12:11
     * @Param:
     * @return:
     */
    private void addTable(XWPFDocument document, List<String> headers, List<List<String>> data) {
        Integer rowNum = 1;
        if (!Objects.isNull(data.get(0))) {
            rowNum = data.get(0).size();
        }
        // 添加表格
        XWPFTable table = document.createTable(rowNum, headers.size()); // 创建一个3行3列的表格
        // 设置表头
        for (int col = 0; col < headers.size(); col++) {
            XWPFTableCell cell = table.getRow(0).getCell(col);
            cell.setText(headers.get(col));
            cell.setWidth("1000");
            addCellCenterStyle(cell);
        }
        // 设置示例数据
        for (int row = 0; row < data.size(); row++) {
            for (int col = 0; col < headers.size(); col++) {
                XWPFTableCell cell = table.getRow(row + 1).getCell(col);
                cell.setText(data.get(row).get(col));
                cell.setWidth("1000");
                addCellCenterStyle(cell);
            }
        }
    }

    /**
     * @author: 张乐焕
     * @Description: 添加水平居中韩国样式
     * @Date: 2023/8/19 12:11
     * @Param:
     * @return:
     */
    private void addCellCenterStyle(XWPFTableCell cell) {
        CTTc ctTc = cell.getCTTc();
        //获取 CTP
        CTP ctP = (ctTc.sizeOfPArray() == 0) ?
                ctTc.addNewP() : ctTc.getPArray(0);
        //获取段落
        XWPFParagraph par = cell.getParagraph(ctP);
        //设置水平居中
        par.setAlignment(ParagraphAlignment.CENTER);
    }
}